<?php
namespace Modules\Ddtalk\Lib;
  //接口需参看dingding文档:
  //http://g.alicdn.com/dingding/opendoc/docs/_server/tab2.html?t=1466131884821

  // Usage:
  //
  // User::get($code);  //code换userid
  // User::getUserId($uniqueId);  //uniqueId换userid
  
  //  $user = User::getUser($userid);  //返回user对象
  //  User::createUser($data); //参数见钉钉文档
  //  User::updateUser($data);//参数见钉钉文档
  //  User::deleteUser($userId); //删除用户
  //  User::batchDeleteUser($userIds);//批量删除用户
  //  
  //  $user = User::getUser($userid);
  //  $user->name = '哈哈'
  //  $user->update(); //更新用户名字
  //  $user->delete(); //删除用户.


class User {
	const API_PATH_GET_USERINFO = '/user/getuserinfo';
	
	const API_USER_GET_USERID = "/user/getUseridByUnionid";
	const API_USER_GET = "/user/get";
	const API_USER_CREATE= "/user/create";
	const API_USER_UPDATE = "/user/update";
	const API_USER_DELETE = "/user/delete";
	const API_USER_DELETE_BATCH = "/user/batchdelete";

	/**
	 * @param $code
	 * @return bool|mixed
	 * @throws Exception
	 * @return mixed
	 *      userid	    员工在企业内的UserID
	 *      deviceId	手机设备号,由钉钉在安装时随机产生
	 *      is_sys	    是否是管理员
	 *      sys_level	级别，三种取值。0:非管理员 1：普通管理员 2：超级管理员
	 */
	public static function get($code) {
		return Util::request(self::API_PATH_GET_USERINFO, array('code'=>$code), true, 'get');
	}

	private $userid;
	private $name;
	private $tel;
	private $workPlace;
	private $remark;
	private $mobile;
	private $email;
	private $active;
	private $orderInDepts;//Map结构的json字符串, key是部门的Id, value是人员在这个部门的排序值
	private $isAdmin;
	private $isBoss;
	private $dingId;
	private $isLeaderInDepts;//在对应的部门中是否为主管, Map结构的json字符串, key是部门的Id, value是人员在这个部门中是否为主管, true表示是, false表示不是
	private $isHide;//是否号码隐藏, true表示隐藏, false表示不隐藏
	private $department;// 	成员所属部门id列表
	private $position;// 	职位信息
	private $avatar;// 	头像url
	private $jobnumber;// 	员工工号
	private $lang;
	private $extattr=null;// 	扩展属性，可以设置多种属性(但手机上最多只能显示10个扩展属性，具体显示哪些属性，请到OA管理后台->设置->通讯录信息设置和OA管理后台->设置->手机端显示信息设置)性

	private $__dirty = [];

	public function &__get($name) {
		return $this->$name;
	}
	public function __set($name, $value) {
		if ( $value === $this->$name || $name == 'userid' || $name=='lang') {
			return;
		}
		// App::debug('set '.$name);
		// App::debug($this->$name);
		// App::debug($value);
		// App::debug(gettype($this->$name));
		// App::debug(gettype($value));
		if ( $this->$name !== $value ) {
			// App::debug('dirty');
			$this->__dirty[$name] = 1;
		} else {
			//App::debug('skip');
		}
		$this->$name = $value;
	}

	protected function __construct($data,$lang='zh_CN') {
		$this->lang = $lang;
		$this->userid = $data['userid'];
		$this->name = $data['name'];
		$this->tel = $data['tel'];
		$this->workPlace = $data['workPlace'];
		$this->remark = $data['remark'];
		$this->mobile = $data['mobile'];
		$this->email = $data['email'];
		$this->active = $data['active'];
		$this->orderInDepts = $data['orderInDepts'];
		$this->isAdmin = $data['isAdmin'];
		$this->isBoss = $data['isBoss'];
		$this->dingId = $data['dingId'];
		$this->isLeaderInDepts = json_decode($data['isLeaderInDepts'],true);
		$this->isHide = $data['isHide'];
		$this->department = $data['department'];
		$this->position = $data['position'];
		$this->avatar = $data['avatar'];
		$this->jobnumber = $data['jobnumber'];
		if (isset($data['extattr'])) {
			$this->extattr = $data['extattr']; 	
		}
	}

	public static function getUserId($unionId) {
		//return (new HttpClient())->jsonGet(self::URL_USER_GET_USERID,['unionid'=>$unionId]);
		return Util::request(self::API_USER_GET_USERID,['unionid'=>$unionId],true,'get');
	}
	
	public static function getUser($userid,$lang='zh_CN') {
		$data = Util::request(self::API_USER_GET,['userid'=>$userid,'lang'=>$lang],true,'get');
	    // $data = (new HttpClient())->jsonGet(self::URL_USER_GET,
	    //  	['userid'=>$userid,'lang'=>$lang]);
	    return new User($data,$lang);
	}

	public static function createUser($createData) {
		return Util::request(self::API_USER_CREATE, $createData,true);
		// $data = (new HttpClient())->jsonGet(self::URL_USER_CREATE,
	 //     	$createData);
		// if ($data['errcode']==0) {
		// 	return true;
		// }
	 //    return false;
	}

	public static function updateUser($updateData) {
		return Util::request(self::API_USER_UPDATE, $updateData);
		// $updateData['userid'] = $userid;
		// return (new HttpClient())->jsonPost(self::URL_USER_UPDATE,$updateData);
	}

    public static function deleteUser($userid) {
    	return Util::request(self::API_USER_DELETE, ['userid'=>$userid],true,'get');
    	// $ret = (new HttpClient())->jsonPost(self::URL_USER_DELETE,['userid'=>$userid]);
    	// if ($ret['errcode']!=0){
    	// 	return true;
    	// } 
    	// return false;
    }

    public static function batchDeleteUser($userids) {
    	return Util::request(self::API_USER_DELETE_BATCH, ['userid'=>$userids]);
    	// $ret =  (new HttpClient())->jsonPost(self::URL_USER_DELETE_BATCH,['useridlist'=>$userids]);
    	// if ($ret['errcode']!=0){
    	// 	return true;
    	// } 
    	// return false;
    }

    public function update() {
    	$data = [];
		//App::debug('user __dirty is'.json_encode($this->__dirty));
		foreach ($this->__dirty as $key => $value ) {
			$data[$key] = $this->$key;
		}
		if (empty($data)) {
			return false;
		} else {
			$data['userid'] = $this->userid;
			return User::updateUser($data);
		}
    }
    public function delete() {
    	return User::deleteUser($this->userid);
    }



}
